package com.bjpowernode.util;

import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ListObjectsRequest;
import com.aliyun.oss.model.ObjectListing;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 将文件上传至oss服务器
 */
public class OSSUtil {
    private static final String accessKeyId = "9RaAgnpS0mb7TFqc";
    private static final String accessKeySecret = "v8VMQwYpHc5tz843diD6PtL4Xq2PwV";
    private static final String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";

    private static final String fileUrl = "https://<bucket>.oss-cn-hangzhou.aliyuncs.com/<key>";

    //指定项目中文件所放的目录
    private static final String directory = "test/";

    //指定项目中文件所放的bucket
    private static final String bucket = "zxp-sit";

    private static final OSS client;

    static {
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSupportCname(true);
        client = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret, clientBuilderConfiguration);
    }

    public static String fileUpload(String filePath) throws FileNotFoundException {
        return fileUpload(bucket,getFileKey(bucket,filePath),filePath);
    }

    //动态生成文件所在目录及文件名
    private static String getFileKey(String bucket,String filePath){
        String fileType = "";
        if (filePath.contains(".")) {
            fileType = filePath.substring(filePath.lastIndexOf("."));
        }
        String marker = null;
        ObjectListing objectListing;
        int fileSize = 0;
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        String data = format.format(new Date());
        String dir = data.substring(2);
        do {
            objectListing = client.listObjects(new ListObjectsRequest(bucket).withMarker(marker).withPrefix(directory +dir));
            marker = objectListing.getNextMarker();
            fileSize += objectListing.getObjectSummaries().size();
        } while (objectListing.isTruncated());
        return directory+dir+"/"+fileSize+fileType;
    }

    private static String fileUpload(String bucket,String key,String filePath) throws FileNotFoundException {
        File file = new File(filePath);
        FileInputStream in = new FileInputStream(file);
        client.putObject(bucket,key,in);
        return fileUrl.replaceAll("<bucket>",bucket).replaceAll("<key>",key);
    }
}
